﻿using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.MODEL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_Receives2 : System.Web.UI.Page
    {
        #region Fields

        private bool _vatChangeFlag = false;

        Main main = new Main();
        IBLL_FIM_Receives r = new B_FIM_Receives();
        D_FIM_Receives r2 = new D_FIM_Receives();
        IBLL_FIM_ReceiveDtls rd = new B_FIM_ReceiveDtls();
        IBLL_FIM_MAS_ReceiveTypes type = new B_FIM_MAS_ReceiveTypes();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_FIM_MAS_Contacts con = new B_FIM_MAS_Contacts();
        IBLL_HRM_PS_Employees emp = new B_HRM_PS_Employees();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_MAS_Methods m = new B_FIM_MAS_Methods();
        IBLL_FIM_MAS_Banks bank = new B_FIM_MAS_Banks();
        IBLL_FIM_MAS_BankBranchs branch = new B_FIM_MAS_BankBranchs();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_FIM_MoneyReturns ret = new B_FIM_MoneyReturns();
        IBLL_FIM_MoneyReturnDtls retd = new B_FIM_MoneyReturnDtls();
        IBLL_FIM_Petitions pet = new B_FIM_Petitions();
        IBLL_ICM_Bid bid = new B_ICM_Bid();
        IBLL_ICM_Bidder bidder = new B_ICM_Bidder();
        IBLL_ICM_BidOfferCollateral bidderCol = new B_ICM_BidOfferCollateral();
        IBLL_ICM_PurchaseOrderContractCollateral poCon = new B_ICM_PurchaseOrderContractCollateral();
        IBLL_ICM_PurchaseOrderPrepayCollateral poPre = new B_ICM_PurchaseOrderPrepayCollateral();
        IBLL_BGM_ProjectOperationReport oprpt = new B_BGM_ProjectOperationReport();
        IBLL_ACM_GENERATE_ACCOUNT_Auto acm = new B_ACM_GENERATE_ACCOUNT_Auto();
        IBLL_CodeGenerate cg = new B_CodeGenerate();
        MailMerge mailMerge = new MailMerge();
        D_FIM_SystemControls sys = new D_FIM_SystemControls();
        int nOffset = 10;

        int tmpRecvSeq = 4105;      
        DataTable dtInvItems = new DataTable();

        #endregion

        #region Events

        //Order events when load page by sequence 
        //: start from Page_Load() to CheckedChanged2()

        protected void Page_Load(object sender, EventArgs e)
        {
            RadComboBox ddl = DropDownList_Contact1.GetComboBox();
            DropDownList_IcmPoSeqContract.Child = ddl;
            DropDownList_IcmPoSeqContract.TxtIncludeVatAmount = txtIncludeVatAmount;
            DropDownList_IcmPoSeqContract.TxtAmount = txtAmount;
            DropDownList_IcmPoSeqContract.Child = ddl;
            DropDownList_IcmPoSeqPrepay.Child = ddl;           

            if (!IsPostBack)
            {
                var sysControls = main.GetSystemControls();
                var year1 = sysControls.default_bgm_year;
                int year = year1.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();

                UpdateUI1("ViewAll");

                LoadDDLFilterBgmSourceSeq();
                LoadDDLFilterReceiveType();
                ddlFilterBgmSourceSeq.SelectedIndex = 0;
                LoadDDLReceiveTypeSeq();
                LoadRBLMethodSeq();
                LoadDDLBankAccSeq();
                LoadBank();
               
                rblMethodSeq.SelectedValue = "1";//เงินสด
                RblModeSelectChanged();
                rblManualReceipt_SelectedIndexChanged(null, null);
                rblMethodSeq_SelectedIndexChanged(null, null);
                CheckedChanged(null, null);
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
                string strSystemName = sys.GetSystemName();
                tblHAI.Visible = strSystemName == "HA";
                panelHAI.Visible = strSystemName == "HA";
            }

            if (RadGrid1.Items.Count > 0 && RadGrid1.SelectedItems.Count > 0)
            {
                cmdPrint1.Visible = true;
                cmdCancelled.Visible = true;
                //AddItmDetails.Enabled = true;
            }
            else
            {
                cmdPrint1.Visible = false;
                cmdCancelled.Visible = false;
                //AddItmDetails.Enabled = false;
            }            
        }

        protected void cmdViewAll1_Click(object sender, EventArgs e)
        {
            UpdateUI1("ViewAll");
            ClearControl1();
        }

        public void LoadGrdMoneyRequestDtls(string strMoneyReqSeq, string strReceiveSeq)
        {
            grdMoneyRequestDtls.DataSource = rd.GetReceiveDtlsAndMoneyRequestDtls(strMoneyReqSeq, strReceiveSeq);
            grdMoneyRequestDtls.DataBind();
        }

        protected void cmdAddNew1_Click(object sender, EventArgs e)
        {
            dpReceiveDate.SetValue(DateTime.Today);
            //dpInvoiceDate.SetValue(DateTime.Today);
            lblReceiveBy.Text = Session["EmpSeq"].ToString();
            lblReceiveByName.Text = Session["UserName"].ToString();
            rblMode.Enabled = true;
            DropDownList_MoneyRequest1.SetSelectedValue("");
            DropDownList_MoneyRequest1.ddlMoneyReqSeq_SelectedIndexChanged(DropDownList_MoneyRequest1, null);
            DropDownList_MoneyRequest1.SetEnable(true);

            UpdateUI1("AddNew");
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            M_FIM_Receives info = new M_FIM_Receives();
            string strReceiveSeq;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiveDate = dpReceiveDate.GetStringValue();
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            string strManualReceipt = rblManualReceipt.SelectedValue;
            string strReceiveMode = rblMode.SelectedValue;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strChequeNo = txtChequeNo.Text;
            string strBranchSeq = null;
            string strBankAccSeq = null;
            string strContactSeq = null; //DropDownList_Contact1.GetSelectedValue();
            string strEmpSeq = null; //DropDownList_Emp1.GetSelectedValue();
            string strTempContact = null;// txtTempContact.Text;
            string strContactPersonSeq = null;
            string strRemarks = txtRemarks.Text;
            string strReceivedBy = lblReceiveBy.Text;

            string strIcmBidRecSeq = null;
            string strIcmBidOffColSeq = null;
            string strIcmPoConColSeq = null;
            string strIcmPoPreColSeq = null;
            string strPetitionSeq = null;// DropDownList_Petition1.GetSelectedValue();
            string strMoneyReqSeq = null;// DropDownList_MoneyRequest1.GetSelectedValue();
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            string strReciveRemark = txtReciveRemark.Text;
            string strSource = "Receive";

            string strAmount = "0";
            string qty = txtQty.Text.Trim();
            string discRate = txtDiscRate.Text.Trim();
            string discount = txtDiscount.Text.Trim();
            string unitPrice = txtUnitPrice.Text.Trim();
            //string strTaxInvCreated = dpInvoiceDate.GetStringValue();

            M_FIM_MAS_Contacts contInfo = new M_FIM_MAS_Contacts();
            M_FIM_MAS_Contacts contAddr = new M_FIM_MAS_Contacts();
            M_HRM_PS_Employees empInfo = new M_HRM_PS_Employees();           

            lblRequireRemarks.Visible = false;

            if (r2.CheckDuplicateReceiptNo(strReceiptNo, null))
            {
                main.MessageAlert(Page, "เลขที่ใบเสร็จรับเงินซ้ำ!!");
                return;
            }

            if (strMethodSeq == "2")
                strBranchSeq = ddlBank.SelectedValue; //DropDownList_BankBranch1.GetSelectedValue();
            else if (strMethodSeq == "3")
                strBankAccSeq = ddlBankAccSeq.SelectedValue;

            switch (strReceiveMode)
            {
                case "1":
                    strReceiveTypeSeq = null;
                    strMoneyReqSeq = DropDownList_MoneyRequest1.GetSelectedValue();
                    strContactSeq = (rbContact2.Checked ? lblContactSeq.Text : null);
                    strEmpSeq = (rbEmp2.Checked ? lblEmpSeq.Text : null);
                    strContactPersonSeq = (rbTemp2.Checked ? lblContactPersonSeq.Text : null);
                    strAmount = lblAmount2.Text;

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    double dAmount = main.ConvertNullDouble(strAmount) ?? 0;
                    double dReturnedAmount = main.ConvertNullDouble(lblAmount2.Text) ?? 0;
                    double dRequestAmount = main.ConvertNullDouble(lblReqAmount.Text) ?? 0;
                    double dLimit = dRequestAmount * 25 / 100;

                    if (dLimit < dAmount)
                    {
                        if (string.IsNullOrEmpty(strRemarks))
                        {
                            lblRequireRemarks.Visible = true;
                            return;
                        }
                    }

                    break;

                case "2":
                    M_ICM_Bidder info1 = new M_ICM_Bidder();
                    M_ICM_PurchaseOrderContractCollateral info2 = new M_ICM_PurchaseOrderContractCollateral();

                    string strIcmBidSeq = null;
                    string strIcmPoSeq = null;

                    strAmount = txtAmount.Text;
                    strContactSeq = (rbContact.Checked ? DropDownList_Contact1.GetSelectedValue() : null);
                    strEmpSeq = (rbEmp.Checked ? DropDownList_Emp1.GetSelectedValue() : null);
                    strTempContact = (rbTemp.Checked ? txtTempContact.Text : null);
                   
                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    if (pnBidSale.Visible)
                    {
                        strIcmBidSeq = ddlIcmBidSeq.SelectedValue;

                        info1.icm_bid_seq = main.ConvertNullInt(strIcmBidSeq);
                        info1.icm_con_seq = main.ConvertNullInt(strContactSeq);
                        info1.icm_receive_date = main.ConvertNullDateTime(strReceiveDate);
                        info1.icm_receive_time = main.ConvertNullTimeSpan(DateTime.Now);
                        // hard code----------------------
                        info1.icm_vat_seq = 2;
                        info1.vat_percent = 7;
                        info1.icm_dur_type_seq = 1;
                        info1.receive_status = "1";
                        info1.offer_status = "0";
                        info1.winner_status = "0";
                        //--------------------------------
                        info1.receive_receipt_no = strReceiptNo;
                        info1.created_by = main.ConvertNullInt(strUserID);
                        info1.created_when = main.ConvertNullDateTime(dtNow);

                        strIcmBidRecSeq = bidder.Insert(info1);
                    }

                    if (pnBidCollateral.Visible)
                    {
                        string strIcmBidderSeq = null;
                        
                        strIcmBidSeq = ddlIcmBidSeqOffer.SelectedValue;
                        strIcmBidderSeq = bidder.GetInfo(strIcmBidSeq, strContactSeq).icm_bidder_seq.ToString();

                        if (strIcmBidderSeq.Length > 0)
                        {
                            info1.icm_bidder_seq = Convert.ToInt32(strIcmBidderSeq);
                            info1.icm_offer_date = main.ConvertNullDateTime(strReceiveDate);
                            info1.icm_offer_time = main.ConvertNullTimeSpan(DateTime.Now);
                            info1.offer_status = "1";
                            info1.updated_by = main.ConvertNullInt(strUserID);
                            info1.updated_when = main.ConvertNullDateTime(dtNow);

                            strIcmBidOffColSeq = bidder.UpdateOffer(info1, strReceiptNo, strAmount);
                        }
                    }

                    if (pnPoContract.Visible)
                    {
                        strIcmPoSeq = DropDownList_IcmPoSeqContract.GetSelectedValue();
                        
                        if (strIcmPoSeq.Length > 0)
                        {
                            info2.icm_col_type_seq = 1;
                            info2.icm_po_con_col_amount = main.ConvertNullDouble(strAmount);
                            info2.icm_po_seq = main.ConvertNullInt(strIcmPoSeq);
                            info2.receipt_no = strReceiptNo;

                            info2.created_by = main.ConvertNullInt(strUserID);
                            info2.created_when = main.ConvertNullDateTime(dtNow);

                            strIcmPoConColSeq = poCon.Insert(info2);
                        }
                    }
                   
                    break;

                case "3":
                    strPetitionSeq = DropDownList_Petition1.GetSelectedValue();
                    strAmount = lblPetitionAmount.Text;

                    break;
            }

            decimal? dVatAmount = txtVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtVatAmount.Text) : 0;
            decimal? dExcludeVatAmount = txtExcludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtExcludeVatAmount.Text) : 0;
            decimal? dVatPercent = txtVatPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtVatPercent.Text) : 0;
            decimal? dTax = txtTaxAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxAmount.Text) : 0;
            decimal? dTaxPercent = txtTaxPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxPercent.Text) : 0;
            decimal? dIncludeVat = txtIncludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtIncludeVatAmount.Text) : 0;

            //ไม่ให้บันทึกถ้ายอดรวมภาษีมูลค่าเพิ่มไม่เท่ากัน
            if (dIncludeVat != dVatAmount + dExcludeVatAmount)
            {
                return;
            }

            info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            info.bgm_year = main.ConvertNullInt(strBgmYear);
            info.receipt_no = strReceiptNo;// ;
            info.ref_no = cg.GetNextCode(TransectionType.FimReceiptNo, strBgmSourceSeq == "1" ? "1" : "2");
            info.receive_date = main.ConvertNullDateTime(strReceiveDate);
            info.receive_type_seq = main.ConvertNullInt(strReceiveTypeSeq);
            info.manual_receipt = strManualReceipt;
            info.receive_mode = strReceiveMode;
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            info.cheque_no = strChequeNo;
            info.branch_seq = main.ConvertNullInt(strBranchSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);            
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.remarks = strRemarks;
            info.amount = main.ConvertNullDouble(strAmount);

            info.received_by = main.ConvertNullInt(strReceivedBy);
            info.icm_bid_rec_seq = main.ConvertNullInt(strIcmBidRecSeq);
            info.icm_bid_off_col_seq = main.ConvertNullInt(strIcmBidOffColSeq);
            info.icm_po_con_col_seq = main.ConvertNullInt(strIcmPoConColSeq);
            info.icm_po_pre_col_seq = main.ConvertNullInt(strIcmPoPreColSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = main.ConvertNullDateTime(dtNow);

            info.vat_amount = dVatAmount;
            info.exclude_vat = dExcludeVatAmount;
            info.vat_percent = dVatPercent;
            info.recive_remark = strReciveRemark;
            info.tax = dTax;
            info.tax_percent = dTaxPercent;
            info.include_vat = dIncludeVat;
            info.source = strSource;
            info.qty = main.ConvertNullInt(qty);
            info.discount_percent = main.ConvertNullDecimal(Math.Abs(decimal.Parse(discRate)));
            info.discount = main.ConvertNullDecimal(discount);
            info.unit_price = main.ConvertNullDecimal(unitPrice);

            if (strTempContact == null)
            {
                if (contInfo == null)
                {
                    if (empInfo != null)
                    {
                        info.temp_contact = empInfo.emp_name;
                    }
                    else
                    {
                        info.temp_contact = "";
                    }
                }
                else
                {
                    info.temp_contact = contInfo.contact_name;
                }
            }
            else
            {
                info.temp_contact = strTempContact;
            }

            if (contAddr == null)
            {
                info.contact_address = txtAddr.Text.Trim(); //(empInfo == null ? txtAddr.Text.Trim() : empInfo.work_area_name);
            }
            else
            {
                info.contact_address = contAddr.address;
            }
                        
            strReceiveSeq = r.Insert(info);
            info.receive_seq = int.Parse(strReceiveSeq);
            RecivLog_Insert(info, "I", "");
            
            updInvItems(info.receive_seq.ToString());  //

            //เมื่อค่า strMoneyReqSeq เป็นค่า null ทำให้เรียกใช้ oprpt.Insert(reportInfo); Error
            if (!string.IsNullOrEmpty(strMoneyReqSeq))
            {
                double dReceiveAmount = Convert.ToDouble(strAmount);
                IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);

                if (mrdInfo.Count > 0)
                {
                    M_BGM_ProjectOperationReport reportInfo = new M_BGM_ProjectOperationReport();

                    reportInfo.bgm_proj_oper_exp_seq = mrdInfo[0].bgm_proj_oper_exp_seq;
                    reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                    reportInfo.used_amount = dReceiveAmount;
                    reportInfo.cal_amount = dReceiveAmount;
                    reportInfo.rpt_type = 8;//คืนเงิน
                    reportInfo.created_by = main.ConvertNullInt(strUserID);
                    reportInfo.created_when = DateTime.Now;

                    oprpt.Insert(reportInfo);
                }

                if (grdMoneyRequestDtls.Visible)
                {
                    foreach (GridDataItem item in grdMoneyRequestDtls.Items)
                    {
                        int nMoneyReqDtlsSeq = Convert.ToInt32(main.WebString(item["money_req_dtls_seq"].Text));
                        RadNumericTextBox txtReceiveDtlsAmount = (RadNumericTextBox)item.FindControl("txtReceiveDtlsAmount");
                        double dAmount = txtReceiveDtlsAmount.Value ?? 0;

                        rd.Insert(new M_FIM_ReceiveDtls()
                        {
                            receive_seq = info.receive_seq,
                            receive_type_seq = nMoneyReqDtlsSeq,
                            amount = dAmount,
                            record_status = "U",
                            created_by = new SsMng().EmpSeqI,
                            created_when = DateTime.Now,
                        });
                    }
                }

                //for (int i = 0; i < mrdInfo.Count; i++)
                //{
                //    double dReqAmount = mrdInfo[i].amount ?? 0;
                //    double dReturnAmount = retd.GetList2(mrdInfo[i].money_req_dtls_seq ?? 0).Sum(o => o.amount ?? 0);//(retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                //    double dRemainAmount = dReqAmount - dReturnAmount;

                //    if (dRemainAmount > 0 && dReceiveAmount > 0)
                //    {
                //        double dUsedAmount = 0;

                //        if (dRemainAmount < dReceiveAmount)
                //        {
                //            dUsedAmount = dRemainAmount;
                //            dReceiveAmount -= dRemainAmount;
                //        }
                //        else
                //        {
                //            dUsedAmount = dReceiveAmount;
                //            dReceiveAmount = 0;
                //        }

                //        M_BGM_ProjectOperationReport reportInfo = new M_BGM_ProjectOperationReport();

                //        reportInfo.bgm_proj_oper_exp_seq = mrd.GetInfo(mrdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                //        reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                //        reportInfo.used_amount = dUsedAmount;
                //        reportInfo.cal_amount = dUsedAmount;
                //        reportInfo.rpt_type = 8;//คืนเงิน
                //        reportInfo.created_by = main.ConvertNullInt(strUserID);
                //        reportInfo.created_when = DateTime.Now;

                //        oprpt.Insert(reportInfo);
                //    }
                //}
            }

            LoadRadGrid1();
            RadGrid1.DataBind();
            UpdateUI1("Insert");
            ClearControl1();

            string script = "alert(\"บันทึกสำเร็จ\");";
            ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            M_FIM_Receives info = new M_FIM_Receives();
            string strReceiveSeq = lblReceiveSeq.Text;
            string strRefNo = lblRefNo.Text;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiveDate = dpReceiveDate.GetStringValue();
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            string strManualReceipt = rblManualReceipt.SelectedValue;
            string strReceiveMode = rblMode.SelectedValue;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strChequeNo = txtChequeNo.Text;
            string strBranchSeq = null;
            string strBankAccSeq = null;
            string strContactSeq = null; //DropDownList_Contact1.GetSelectedValue();
            string strEmpSeq = null; //DropDownList_Emp1.GetSelectedValue();
            string strTempContact = null;// txtTempContact.Text;
            string strContactPersonSeq = null;
            string strRemarks = txtRemarks.Text;
            string strReceivedBy = lblReceiveBy.Text;
            string strAmount = txtAmount.Text;

            string strIcmBidSeq = null;
            string strIcmBidSeqOffer = null;
            string strIcmBidRecSeq = null;
            string strIcmBidOffColSeq = null;
            string strIcmPoConColSeq = null;
            string strIcmPoPreColSeq = null;
            string strPetitionSeq = null;// DropDownList_Petition1.GetSelectedValue();
            string strMoneyReqSeq = null;// DropDownList_MoneyRequest1.GetSelectedValue();
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;

            string strReciveRemark = txtReciveRemark.Text;
            string qty = txtQty.Text.Trim();
            string discRate = txtDiscRate.Text.Trim();
            string discount = txtDiscount.Text.Trim();
            string unitPrice = txtUnitPrice.Text.Trim();
            //DateTime taxInvCreated = main.ConvertNullDateTime(dpInvoiceDate.GetDateValue()).Value;

            M_FIM_MAS_Contacts contInfo = new M_FIM_MAS_Contacts();
            M_FIM_MAS_Contacts contAddr = new M_FIM_MAS_Contacts();
            M_HRM_PS_Employees empInfo = new M_HRM_PS_Employees();

            if (r2.CheckDuplicateReceiptNo(strReceiptNo, strReceiveSeq))
            {
                main.MessageAlert(Page, "เลขที่ใบเสร็จรับเงินซ้ำ!!");
                return;
            }

            if (strMethodSeq == "2")
                strBranchSeq = ddlBank.SelectedValue; //DropDownList_BankBranch1.GetSelectedValue();
            else if (strMethodSeq == "3")
                strBankAccSeq = ddlBankAccSeq.SelectedValue;

            switch (strReceiveMode)
            {
                case "1":
                    strMoneyReqSeq = DropDownList_MoneyRequest1.GetSelectedValue();
                    strContactSeq = (rbContact2.Checked ? lblContactSeq.Text : null);
                    strEmpSeq = (rbEmp2.Checked ? lblEmpSeq.Text : null);
                    strContactPersonSeq = (rbTemp2.Checked ? lblContactPersonSeq.Text : null);
                    strAmount = lblAmount2.Text;

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    double dAmount = main.ConvertNullDouble(strAmount) ?? 0;
                    double dReturnedAmount = main.ConvertNullDouble(lblAmount2.Text) ?? 0;
                    double dRequestAmount = main.ConvertNullDouble(lblReqAmount.Text) ?? 0;
                    double dLimit = dRequestAmount * 25 / 100;

                    if (dLimit < dAmount)
                    {
                        if (string.IsNullOrEmpty(strRemarks))
                        {
                            lblRequireRemarks.Visible = true;
                            return;
                        }
                    }
                    break;
                case "2":
                    strAmount = txtAmount.Text;
                    strContactSeq = (rbContact.Checked ? DropDownList_Contact1.GetSelectedValue() : null);
                    strEmpSeq = (rbEmp.Checked ? DropDownList_Emp1.GetSelectedValue() : null);
                    strTempContact = (rbTemp.Checked ? txtTempContact.Text : null);
                    strIcmBidSeq = ddlIcmBidSeq.SelectedValue;
                    strIcmBidSeqOffer = ddlIcmBidSeqOffer.SelectedValue;
                    strIcmPoConColSeq = DropDownList_IcmPoSeqContract.GetSelectedValue();
                    strIcmPoPreColSeq = DropDownList_IcmPoSeqPrepay.GetSelectedValue();
                    M_ICM_Bidder info1 = new M_ICM_Bidder();
                    M_ICM_PurchaseOrderContractCollateral info2 = new M_ICM_PurchaseOrderContractCollateral();
                    M_ICM_BidOfferCollateral info3 = new M_ICM_BidOfferCollateral();

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);


                    if (pnBidSale.Visible)
                    {
                        strIcmBidRecSeq = hIcmBidRecSeq.Text;

                        info1.icm_bidder_seq = Convert.ToInt32(strIcmBidRecSeq);
                        info1.icm_bid_seq = main.ConvertNullInt(strIcmBidSeq);
                        info1.icm_con_seq = main.ConvertNullInt(strContactSeq);
                        info1.icm_receive_date = main.ConvertNullDateTime(strReceiveDate);
                        info1.icm_receive_time = main.ConvertNullTimeSpan(DateTime.Now);
                        // hard code----------------------
                        info1.icm_vat_seq = 2;
                        info1.vat_percent = 7;
                        info1.icm_dur_type_seq = 1;
                        info1.receive_status = "1";
                        info1.offer_status = "0";
                        info1.winner_status = "0";
                        //--------------------------------
                        info1.receive_receipt_no = strReceiptNo;
                        info1.created_by = main.ConvertNullInt(strUserID);
                        info1.created_when = main.ConvertNullDateTime(dtNow);

                        strIcmBidRecSeq = bidder.Insert(info1);
                    }                  

                    break;
            }

            decimal? dVatAmount = txtVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtVatAmount.Text) : 0;
            decimal? dExcludeVatAmount = txtExcludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtExcludeVatAmount.Text) : 0;
            decimal? dVatPercent = txtVatPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtVatPercent.Text) : 0;
            decimal? dTax = txtTaxAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxAmount.Text) : 0;
            decimal? dTaxPercent = txtTaxPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxPercent.Text) : 0;
            decimal? dIncludeVat = txtIncludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtIncludeVatAmount.Text) : 0;

            //ไม่ให้บันทึกถ้ายอดรวมภาษีมูลค่าเพิ่มไม่เท่ากัน
            if (dIncludeVat != dVatAmount + dExcludeVatAmount)
            {
                return;
            }

            info.receive_seq = Convert.ToInt32(strReceiveSeq);
            info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            info.bgm_year = main.ConvertNullInt(strBgmYear);
            info.receipt_no = strReceiptNo;
            info.ref_no = strRefNo;
            info.receive_date = main.ConvertNullDateTime(strReceiveDate);
            info.receive_type_seq = main.ConvertNullInt(strReceiveTypeSeq);
            info.manual_receipt = strManualReceipt;
            info.receive_mode = strReceiveMode;
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            info.cheque_no = strChequeNo;
            info.branch_seq = main.ConvertNullInt(strBranchSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.temp_contact = strTempContact;
            info.remarks = strRemarks;
            info.amount = main.ConvertNullDouble(strAmount);
            
            info.received_by = main.ConvertNullInt(strReceivedBy);
            info.icm_bid_rec_seq = main.ConvertNullInt(strIcmBidRecSeq);
            info.icm_bid_off_col_seq = main.ConvertNullInt(strIcmBidOffColSeq);
            info.icm_po_con_col_seq = main.ConvertNullInt(strIcmPoConColSeq);
            info.icm_po_pre_col_seq = main.ConvertNullInt(strIcmPoPreColSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = main.ConvertNullDateTime(dtNow);

            info.vat_amount = dVatAmount;
            info.exclude_vat = dExcludeVatAmount;
            info.vat_percent = dVatPercent;
            info.recive_remark = strReciveRemark;
            info.tax = dTax;
            info.tax_percent = dTaxPercent;
            info.include_vat = dIncludeVat;

            info.qty = main.ConvertNullInt(qty);
            info.discount_percent = main.ConvertNullDecimal(discRate);
            info.discount = main.ConvertNullDecimal(discount);
            info.unit_price = main.ConvertNullDecimal(unitPrice);
            
            if (strTempContact == null)
            {
                if (contInfo == null)
                {
                    if (empInfo != null)
                    {
                        info.temp_contact = empInfo.emp_name;
                    }
                    else
                    {
                        info.temp_contact = "";
                    }
                }
                else
                {
                    info.temp_contact = contInfo.contact_name;
                }
            }
            else
            {
                info.temp_contact = strTempContact;
            }

            if (contAddr == null)
            {
                info.contact_address = txtAddr.Text.Trim();  //(empInfo == null ? txtAddr.Text.Trim() : empInfo.work_area_name);
            }
            else
            {
                info.contact_address = contAddr.address;
            }

            r.Update(info);

            //เมื่อค่า strMoneyReqSeq เป็นค่า null ทำให้เรียกใช้ oprpt.Insert(reportInfo); Error
            if (!string.IsNullOrEmpty(strMoneyReqSeq))
            {
                double dReceiveAmount = Convert.ToDouble(strAmount);
                IList<M_BGM_ProjectOperationReport> reportInfo = oprpt.GetFull(null, null, null, null, null, null, null, null
                    , null, null, Convert.ToInt32(strReceiveSeq));

                if (grdMoneyRequestDtls.Visible)
                {
                    foreach (GridDataItem item in grdMoneyRequestDtls.Items)
                    {
                        int nReceiveDtlsSeq = main.ConvertNullInt(main.WebString(item["receive_dtls_seq"].Text)) ?? -1;
                        int nMoneyReqDtlsSeq = Convert.ToInt32(main.WebString(item["money_req_dtls_seq"].Text));
                        int? nReceiveTypeSeq = main.ConvertNullInt(main.WebString(item["receive_type_seq"].Text));
                        int nReceiveSeq = Convert.ToInt32(main.WebString(item["receive_seq"].Text));
                        RadNumericTextBox txtReceiveDtlsAmount = (RadNumericTextBox)item.FindControl("txtReceiveDtlsAmount");
                        double dAmount = txtReceiveDtlsAmount.Value ?? 0;

                        if (nReceiveDtlsSeq > 0)
                        {
                            rd.Update(new M_FIM_ReceiveDtls()
                            {
                                receive_dtls_seq = nReceiveDtlsSeq,
                                receive_seq = nReceiveSeq,
                                receive_type_seq = nMoneyReqDtlsSeq,
                                amount = dAmount,
                                record_status = "U",
                                updated_by = new SsMng().EmpSeqI,
                                updated_when = DateTime.Now,
                            });
                        }
                        else
                        {
                            rd.Insert(new M_FIM_ReceiveDtls()
                            {
                                receive_seq = nReceiveSeq,
                                receive_type_seq = nMoneyReqDtlsSeq,
                                amount = dAmount,
                                record_status = "U",
                                created_by = new SsMng().EmpSeqI,
                                created_when = DateTime.Now,
                            });
                        }
                    }
                }

                if (reportInfo.Count == 1)
                {
                    reportInfo[0].used_amount = dReceiveAmount;
                    reportInfo[0].cal_amount = dReceiveAmount;
                    reportInfo[0].updated_by = main.ConvertNullInt(strUserID);
                    reportInfo[0].updated_when = DateTime.Now;

                    oprpt.Update(reportInfo[0]);
                }
                else if (reportInfo.Count > 1)
                {
                    reportInfo[0].used_amount = dReceiveAmount;
                    reportInfo[0].cal_amount = dReceiveAmount;
                    reportInfo[0].updated_by = main.ConvertNullInt(strUserID);
                    reportInfo[0].updated_when = DateTime.Now;

                    oprpt.Update(reportInfo[0]);

                    for (int i = 1; i < reportInfo.Count; i++)
                    {
                        oprpt.Delete(reportInfo[i]);
                    }
                }
                //}
                //for (int i = 0; i < mrdInfo.Count; i++)
                //{
                //    double dReqAmount = mrdInfo[i].amount ?? 0;
                //    double dReturnAmount = retd.GetList2(mrdInfo[i].money_req_dtls_seq ?? 0).Sum(o => o.amount ?? 0);//(retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                //    double dRemainAmount = dReqAmount - dReturnAmount;

                //    if (dRemainAmount > 0 && dReceiveAmount > 0)
                //    {
                //        double dUsedAmount = 0;

                //        if (dRemainAmount < dReceiveAmount)
                //        {
                //            dUsedAmount = dRemainAmount;
                //            dReceiveAmount -= dRemainAmount;
                //        }
                //        else
                //        {
                //            dUsedAmount = dReceiveAmount;
                //            dReceiveAmount = 0;
                //        }

                //        var bgm_proj_oper_exp_seq = mrd.GetInfo(mrdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                //        M_BGM_ProjectOperationReport reportInfo = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null, Convert.ToInt32(strReceiveSeq)).Where(o => o.bgm_proj_oper_exp_seq == bgm_proj_oper_exp_seq).FirstOrDefault();

                //        if (reportInfo != null)
                //        {
                //            reportInfo.used_amount = dUsedAmount;
                //            reportInfo.cal_amount = dUsedAmount;
                //            reportInfo.updated_by = main.ConvertNullInt(strUserID);
                //            reportInfo.updated_when = DateTime.Now;

                //            oprpt.Update(reportInfo);
                //        }
                //        else
                //        {
                //            reportInfo = new M_BGM_ProjectOperationReport();
                //            reportInfo.bgm_proj_oper_exp_seq = bgm_proj_oper_exp_seq;
                //            reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                //            reportInfo.used_amount = dUsedAmount;
                //            reportInfo.cal_amount = dUsedAmount;
                //            reportInfo.rpt_type = 8;//คืนเงิน
                //            reportInfo.created_by = main.ConvertNullInt(strUserID);
                //            reportInfo.created_when = DateTime.Now;

                //            oprpt.Insert(reportInfo);
                //        }

                //    }
                //}
            }

            LoadRadGrid1();
            RadGrid1.DataBind();
            UpdateUI1("Update");
            ClearControl1();

            string script = "alert(\"บันทึกสำเร็จ\");";
            ScriptManager.RegisterStartupScript(this, GetType(),"ServerControlScript", script, true);
        }

        protected void cmdEdit1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                UpdateUI1("Edit");

                GridDataItem item = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex];
                string strReceiveSeq = main.WebString(item["receive_seq"].Text);
                string strReceiptNo = main.WebString(item["receipt_no"].Text);
                string strRefNo = main.WebString(item["ref_no"].Text);
                string strReceiveDate = main.WebString(item["receive_date"].Text);
                string strReceiveTypeSeq = main.WebString(item["receive_type_seq"].Text);
                string strManualReceipt = main.WebString(item["manual_receipt"].Text);
                string strReceiveMode = main.WebString(item["receive_mode"].Text);
                string strMethodSeq = main.WebString(item["method_seq"].Text);
                string strChequeNo = main.WebString(item["cheque_no"].Text);
                string strBranchSeq = main.WebString(item["branch_seq"].Text);
                string strBankID = main.WebString(item["bank_id"].Text);
                string strBankName = main.WebString(item["bank_name"].Text);
                string strBranchID = main.WebString(item["branch_id"].Text);
                string strBranchName = main.WebString(item["branch_name"].Text);
                string strBankAccSeq = main.WebString(item["bank_acc_seq"].Text);
                
                string strContactSeq = main.WebString(item["contact_seq"].Text);
                string strContactName = main.WebString(item["contact_name"].Text);
                string strEmpSeq = main.WebString(item["emp_seq"].Text);
                string strEmpName = main.WebString(item["emp_name"].Text);
                string strTempContact = main.WebString(item["temp_contact"].Text);
                
                string strReceivedBy = main.WebString(item["received_by"].Text);
                string strReceivedByName = main.WebString(item["received_by_name"].Text);
                string strRemarks = main.WebString(item["remarks"].Text);

                string strIcmBidRecSeq = main.WebString(item["icm_bid_rec_seq"].Text);
                string strIcmBidOffColSeq = main.WebString(item["icm_bid_off_col_seq"].Text);
                string strIcmPoConColSeq = main.WebString(item["icm_po_con_col_seq"].Text);
                string strIcmPoPreColSeq = main.WebString(item["icm_po_pre_col_seq"].Text);
                string strIcmDnPenSeq = main.WebString(item["icm_dn_pen_seq"].Text);
                string strIcmPoInstalSeq = main.WebString(item["icm_po_instal_seq"].Text);
                string strIcmStockmmSeq = main.WebString(item["icm_stockmm_seq"].Text);

                string strPetitionSeq = main.WebString(item["petition_seq"].Text);
                string strMoneyReqSeq = main.WebString(item["money_req_seq"].Text);
                string strReciveRemark = main.WebString(item["recive_remark"].Text);
                string dTaxPercent = main.WebString(item["tax_percent"].Text);
                string dTax = main.WebString(item["tax"].Text);
                string dIncludeVat = main.WebString(item["include_vat"].Text);

                string qty = main.WebString(item["qty"].Text); 
                string dDiscRate = main.WebString(item["discount_percent"].Text);
                string dDisc = main.WebString(item["discount"].Text);
                string dUnitPrice = main.WebString(item["unit_price"].Text);
                string strContAddr = main.WebString(item["contact_address"].Text);

                lblReceiveSeq.Text = main.WebString(strReceiveSeq);
                txtReceiptNo.Text = main.WebString(strReceiptNo);
                lblRefNo.Text = main.WebString(strRefNo);
                dpReceiveDate.SetValue(main.WebString(strReceiveDate));
                //dpInvoiceDate.SetValue(main.WebString(strTaxInvCreated));
                ddlReceiveTypeSeq.SelectedValue = main.WebString(strReceiveTypeSeq);
                ddlReceiveTypeSeq_SelectedIndexChanged(null, null);
                rblManualReceipt.SelectedValue = main.WebString(strManualReceipt);
                rblManualReceipt_SelectedIndexChanged(null, null);
                rblMode.SelectedValue = main.WebString(strReceiveMode);
                rblMode_SelectedIndexChanged(null, null);
                rblMethodSeq.SelectedValue = main.WebString(strMethodSeq);
                rblMethodSeq_SelectedIndexChanged(null, null);
                txtChequeNo.Text = main.WebString(strChequeNo);
                ddlBank.SelectedValue = main.WebString(strBranchSeq);
              
                ddlBankAccSeq.SelectedValue = main.WebString(strBankAccSeq);

                lblReceiveBy.Text = main.WebString(strReceivedBy);
                lblReceiveByName.Text = main.WebString(strReceivedByName);
                txtRemarks.Text = main.WebString(strRemarks);
                txtReciveRemark.Text = main.WebString(strReciveRemark);
                txtTaxPercent.Text = main.WebString(dTaxPercent);
                txtTaxAmount.Text = main.WebString(dTax);
                txtIncludeVatAmount.Text = main.WebString(dIncludeVat);

                txtQty.Text = main.WebString(qty);
                txtUnitPrice.Text = main.WebString(dUnitPrice);
                txtDiscRate.Text = main.WebString(dDiscRate);
                txtDiscount.Text = main.WebString(dDisc);
                txtAddr.Text = main.WebString(strContAddr);

                //================= รอ FIMS =======================
                strIcmBidRecSeq = main.WebString(strIcmBidRecSeq);
                strIcmBidOffColSeq = main.WebString(strIcmBidOffColSeq);
                strIcmPoConColSeq = main.WebString(strIcmPoConColSeq);
                strIcmPoPreColSeq = main.WebString(strIcmPoPreColSeq);

                hIcmBidRecSeq.Text = main.WebString(strIcmBidRecSeq);
                hIcmBidOffColSeq.Text = main.WebString(strIcmBidOffColSeq);
                hIcmPoConColSeq.Text = main.WebString(strIcmPoConColSeq);
                hIcmPoPreColSeq.Text = main.WebString(strIcmPoPreColSeq);

                if (main.WebString(strIcmBidRecSeq).Length > 0)
                {

                    ddlIcmBidSeqSetSelectedValue(main.WebString(strIcmBidRecSeq), main.WebString(strContactSeq));                   
                }

                if (strIcmBidOffColSeq.Length > 0)
                {
                    ddlIcmBidSeqOfferSetSelectedValue(strIcmBidOffColSeq, strContactSeq);
                    ddlIcmBidSeqOffer_SelectedIndexChanged(null, null);
                }

                if (strIcmPoConColSeq.Length > 0)
                {
                    DropDownList_IcmPoSeqContract.SetSelectedValue(strIcmPoConColSeq);
                    DropDownList_IcmPoSeqContract.ddlIcmPoSeq_SelectedIndexChanged(null, null);
                }

                if (strIcmPoPreColSeq.Length > 0)
                {
                    DropDownList_IcmPoSeqPrepay.SetSelectedValue(strIcmPoPreColSeq);
                    DropDownList_IcmPoSeqPrepay.ddlIcmPoSeq_SelectedIndexChanged(null, null);
                }
                //================================================

                switch (main.WebString(strReceiveMode))
                {
                    case "1":
                        DropDownList_MoneyRequest1.SetSelectedValue(main.WebString(strMoneyReqSeq));
                        DropDownList_MoneyRequest1.SetEnable(false);
                        lblAmount2.Text = main.WebString(item["amount"].Text);
                        PanelBorrow.Visible = true;// main.WebString(item["event_seq"].Text) == "16";

                        if (PanelBorrow.Visible)
                        {
                            M_FIM_MoneyRequests mrInfo = mr.GetInfo(main.WebString(strMoneyReqSeq), main.WebString(strReceiveSeq));
                            lblReqAmount.Text = (mrInfo.total_amount != null ? mrInfo.total_amount.Value.ToString("#,##0.00") : "0.00");
                            //lblReturnAmount.Text = (mrInfo.return_amount ?? 0 + mrInfo.receive_amount ?? 0).ToString("#,##0.00");
                            LoadGrdMoneyRequestDtls(main.WebString(strMoneyReqSeq), main.WebString(strReceiveSeq));
                        }

                        break;
                    case "2":
                        if (main.WebString(strContactSeq).Length > 0)
                        {
                            rbContact.Checked = true;
                            rbEmp.Checked = false;
                            rbTemp.Checked = false;
                            CheckedChanged(null, null);
                            DropDownList_Contact1.SetSelectedValue(strContactSeq);
                        }
                        else if (main.WebString(strEmpSeq).Length > 0)
                        {
                            rbContact.Checked = false;
                            rbEmp.Checked = true;
                            rbTemp.Checked = false;
                            CheckedChanged(null, null);
                            DropDownList_Emp1.SetSelectedValue(strEmpSeq);
                        }
                        else
                        {
                            rbContact.Checked = false;
                            rbEmp.Checked = false;
                            rbTemp.Checked = true;
                            CheckedChanged(null, null);
                            txtTempContact.Text = strTempContact;
                        }
                        txtAmount.Text = main.WebString(item["amount"].Text);
                        txtVatAmount.Text = main.WebString(item["vat_amount"].Text);
                        txtExcludeVatAmount.Text = main.WebString(item["exclude_vat"].Text);
                        txtVatPercent.Text = main.WebString(item["vat_percent"].Text);

                        break;
                    case "3":
                        DropDownList_Petition1.SetSelectedValue(main.WebString(strPetitionSeq));
                        break;
                }

                rblMode.Enabled = false;
                lbtnAddItmDetails.Enabled = false;      
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการที่ต้องการแก้ไข");
            }

            radInvItems.DataSource = getInvItems(lblReceiveSeq.Text.Trim());
            radInvItems.Rebind();
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                M_FIM_Receives info = new M_FIM_Receives();
                string strUserID = Session["EmpSeq"].ToString();
                DateTime dtNow = DateTime.Now;
                string strReceiveSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_seq"].Text;
                string strReceiptNo = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receipt_no"].Text;
                string strRefNo = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["ref_no"].Text;

                info.receive_seq = Convert.ToInt32(strReceiveSeq);
                info.updated_by = main.ConvertNullInt(strUserID);
                info.updated_when = main.ConvertNullDateTime(dtNow);
                info.receipt_no = strReceiptNo;
                info.ref_no = strRefNo;

                RecivLog_Deleted(info);
                r.Delete(info);                

                var reportInfoList = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null
                    , main.ConvertNullInt(strReceiveSeq));

                foreach (var reportInfo in reportInfoList)
                {
                    reportInfo.updated_by = main.ConvertNullInt(strUserID);
                    reportInfo.updated_when = main.ConvertNullDateTime(dtNow);
                    oprpt.Delete(reportInfo);
                }

                LoadRadGrid1();
                RadGrid1.DataBind();
            }
        }

        protected void ddlFilterReceiveType_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid1();
            LoadDDLReceiveTypeSeq();
            RadGrid1.DataBind();

            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                , txtBgmYear.Text, true, null, null);
            DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                    , txtBgmYear.Text, null, false, null, null);

            LoadDDLBankAccSeq();
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLFilterReceiveType();
            LoadRadGrid1();
            LoadDDLReceiveTypeSeq();
            RadGrid1.DataBind();

            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                , txtBgmYear.Text, true, null, null);
            DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                    , txtBgmYear.Text, null, false, null, null);

            LoadDDLBankAccSeq();
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadRadGrid1();
            RadGrid1.DataBind();

            lblBgmYear.Text = txtBgmYear.Text;
            //DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
            //    , txtBgmYear.Text, true, null, null);
        }

        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            hdReceiveSeq.Value = string.Empty;
            if (e.CommandName == "RowClick" && e.Item is GridDataItem)
            {
                e.Item.Selected = true;
                string strReceiveSeq = e.Item.OwnerTableView.Items[e.Item.ItemIndex]["receive_seq"].Text;
                hdReceiveSeq.Value = strReceiveSeq;
                Session["ReportSeq"] = strReceiveSeq;
            }
        }

        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid1();
            }
        }

        protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                string strReceiptNo = main.WebString(((GridDataItem)RadGrid1.SelectedItems[0])["receipt_no"].Text);
               
                hdReceiveSeq.Value = main.WebString(((GridDataItem)RadGrid1.SelectedItems[0])["receive_seq"].Text);
            }
        }

        protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                var strSeq = dataBoundItem["receive_seq"].Text;
                LinkButton lbtnadd = (LinkButton)dataBoundItem.FindControl("cmdPrintPopup");
                lbtnadd.Visible = false;
                if (!String.IsNullOrEmpty(strSeq))
                {
                    var lst = acm.GetListDetail(Convert.ToInt32(strSeq), "fim_receives");
                    if (lst.Count > 0)
                        lbtnadd.Visible = true;
                }

                var RecordStatus = dataBoundItem["record_status"].Text;

                if (RecordStatus == "C")
                {
                    dataBoundItem.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void rblMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            RblModeSelectChanged();
        }

        protected void rblManualReceipt_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtReceiptNo.Enabled = (rblManualReceipt.SelectedValue == "1");
        }

        protected void rblMethodSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strMethodSeq = rblMethodSeq.SelectedValue;

            switch (strMethodSeq)
            {
                case "1":
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = false;
                    txtReciveRemark.Visible = false;

                    break;
                case "2":
                    PanelCheque.Visible = true;
                    PanelTransfer.Visible = false;
                    txtReciveRemark.Visible = false;

                    break;
                case "3":
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = true;
                    txtReciveRemark.Visible = true;

                    break;
                case "4":
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = false;

                    break;
            }
        }

        protected void ddlBank_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                LoadBranch();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }
        }       

        protected void ddlReceiveTypeSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;

            if (strReceiveTypeSeq.Length > 0)
            {
                M_FIM_MAS_ReceiveTypes info = type.GetInfo(strReceiveTypeSeq);

                switch (info.inv_connect_type)
                {
                    case "0":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        DropDownList_Emp1.Visible = false;
                        rbEmp.Enabled = true;
                        rbTemp.Enabled = true;
                        break;
                    case "1":
                        pnBidSale.Visible = true;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "2":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = true;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "3":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = true;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "4":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = true;
                        rbEmp.Enabled = true;
                        rbTemp.Enabled = true;
                        break;
                }
            }
        }

        protected void ddlIcmBidSeq_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
        {
            LoadIcmBidSeq(e);
        }

        protected void ddlIcmBidSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strValue = ddlIcmBidSeq.SelectedValue;
            DropDownList_Contact1.LoadControl(null, null);

            txtAmount.Text = bidder.AmountBidder(strValue);
        }

        protected void ddlIcmBidSeqOffer_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
        {
            LoadIcmBidSeqOffer(e);
        }

        protected void ddlIcmBidSeqOffer_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strValue = ddlIcmBidSeqOffer.SelectedValue;
            DropDownList_Contact1.LoadControl(null, null, "Offer", strValue);
        }

        protected void CheckedChanged(object sender, EventArgs e)
        {
            bool bContact = rbContact.Checked;
            bool bEmp = rbEmp.Checked;
            bool bTemp = rbTemp.Checked;

            DropDownList_Contact1.GetComboBox().Enabled = bContact;
            DropDownList_Emp1.GetComboBox().Enabled = bEmp;
            txtTempContact.Enabled = bTemp;
            txtAddr.Enabled = true;

            DropDownList_Contact1.SetSelectedValue("");
            DropDownList_Emp1.SetSelectedValue("");            
        }

        protected void txtIncludeVatAmount_TextChanged(object sender, EventArgs e)
        {
            this._vatChangeFlag = true;
            CalculateVat();
        }

        protected void txtVatPercent_TextChanged(object sender, EventArgs e)
        {
            this._vatChangeFlag = true;
            CalculateVat();
        }

        protected void txtVatAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateVat();
        }

        protected void txtExcludeVatAmount_TextChanged(object sender, EventArgs e)
        {
            //CalculateVat();
        }

        protected void txtTaxPercent_TextChanged(object sender, EventArgs e)
        {
            CalculateVat();
        }

        protected void CheckedChanged2(object sender, EventArgs e)
        {
            bool bContact2 = rbContact2.Checked;
            bool bEmp2 = rbEmp2.Checked;
            bool bTemp2 = rbTemp2.Checked;

            lblContactName.Visible = bContact2;
            lblEmpName.Visible = bEmp2;
            lblContactPersonName.Visible = bTemp2;
        }

        protected void txtUnitPrice_TextChanged(object sender, EventArgs e)
        {
            //ให้ใส่ราคาต่อหน่วยแต่ยังไม่ต้องคำนวณ
            //CalculateVat();
        }

        protected void txtQty_TextChanged(object sender, EventArgs e)
        {
            CalculateVat();
        }

        protected void ddlRemarkTemplate_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            txtRemarks.Text = ddlRemarkTemplate.SelectedValue;
            txtQty.Text = "1";
            txtTaxPercent.Text = "0";
            txtDiscRate.Text = "0";
        }

        protected void txtDiscRate_TextChanged(object sender, EventArgs e)
        {
            CalculateVat();
        }

        protected void cmdCancelled_Click(object sender, EventArgs e)
        {
            //int invNo = int.Parse(getInvNo());
            M_FIM_Receives info = new M_FIM_Receives();
            GridDataItem item = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex];

            string receiptNo = main.WebString(item["receipt_no"].Text);
            string refNo = main.WebString(item["ref_no"].Text);
            string strUserID = Session["EmpSeq"].ToString();

            //info.receive_seq = Convert.ToInt32(main.WebString(item["receive_seq"].Text));
            //info.bgm_source_seq = main.ConvertNullInt(main.WebString(item["bgm_source_seq"].Text));
            //info.bgm_year = main.ConvertNullInt(txtBgmYear.Text);
            //info.receipt_no = ""; //(invNo+1).ToString(); ยกเลิกการทำ Dummy เลขที่ใบเสร็จ เพราะผู้ใช้สับสน
            //info.ref_no = refNo;
            //info.receive_date = main.ConvertNullDateTime(main.WebString(item["receive_date"].Text));
            //info.receive_type_seq = main.ConvertNullInt(main.WebString(item["receive_type_seq"].Text));
            //info.manual_receipt = main.WebString(item["manual_receipt"].Text);
            //info.receive_mode = main.WebString(item["receive_mode"].Text);
            //info.method_seq = main.ConvertNullInt(main.ConvertNullDecimal(main.WebString(item["method_seq"].Text)));
            //info.cheque_no = main.WebString(item["cheque_no"].Text);
            //info.branch_seq = main.ConvertNullInt(main.WebString(item["branch_seq"].Text));
            //info.bank_acc_seq = main.ConvertNullInt(main.WebString(item["bank_acc_seq"].Text));
            //info.contact_seq = main.ConvertNullInt(main.WebString(item["contact_seq"].Text));            
            //info.emp_seq = main.ConvertNullInt(main.WebString(item["emp_seq"].Text));
            //info.temp_contact = main.WebString(item["temp_contact"].Text);
            //info.remarks = main.WebString(item["remarks"].Text);
            //info.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));

            //info.received_by = main.ConvertNullInt(main.WebString(item["received_by"].Text));
            //info.icm_bid_rec_seq = main.ConvertNullInt(main.WebString(item["icm_bid_rec_seq"].Text));
            //info.icm_bid_off_col_seq = main.ConvertNullInt(main.WebString(item["icm_bid_off_col_seq"].Text));
            //info.icm_po_con_col_seq = main.ConvertNullInt(main.WebString(item["icm_po_con_col_seq"].Text));
            //info.icm_po_pre_col_seq = main.ConvertNullInt(main.WebString(item["icm_po_pre_col_seq"].Text));
            //info.petition_seq = main.ConvertNullInt(main.WebString(item["petition_seq"].Text));
            //info.money_req_seq = main.ConvertNullInt(main.WebString(item["money_req_seq"].Text));      

            //info.vat_amount = main.ConvertNullDecimal(main.WebString(item["vat_amount"].Text));
            //info.exclude_vat = main.ConvertNullDecimal(main.WebString(item["exclude_vat"].Text));
            //info.vat_percent = main.ConvertNullDecimal(main.WebString(item["vat_percent"].Text));
            //info.recive_remark = main.WebString(item["recive_remark"].Text);
            //info.tax = main.ConvertNullDecimal(main.WebString(item["tax"].Text));
            //info.tax_percent = main.ConvertNullDecimal(main.WebString(item["tax_percent"].Text));
            //info.include_vat = main.ConvertNullDecimal(main.WebString(item["include_vat"].Text));

            //info.qty = main.ConvertNullInt(main.WebString(item["qty"].Text));
            //info.discount_percent = main.ConvertNullDecimal(main.WebString(item["discount_percent"].Text));
            //info.discount = main.ConvertNullDecimal(main.WebString(item["discount"].Text));
            //info.unit_price = main.ConvertNullDecimal(main.WebString(item["unit_price"].Text));
            //info.created_when = main.ConvertNullDateTime(main.WebString(item["created_when"].Text));
            //info.temp_contact = main.WebString(item["temp_contact"].Text);
            //info.contact_address = main.WebString(item["contact_address"].Text);
            //info.created_by = main.ConvertNullInt(strUserID);

            //string receiveSeq = r.Insert(info);
            Receives_Update(main.WebString(item["receive_seq"].Text), strUserID);
            RecivLog_Update(info.receive_seq.ToString(), strUserID);

            //info.receive_seq = int.Parse(receiveSeq);

            //RecivLog_Insert(info, "R", receiptNo);                        
        }
       
        protected void radInvItems_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            radInvItems.DataSource = dtInvItems;
        }       

        #endregion

        #region Private Methods

        private void UpdateUI1(string strCommand)
        {
            switch (strCommand)
            {
                case "ViewAll":
                case "Insert":
                case "Update":
                    cmdViewAll1.Visible = false;
                    cmdAddNew1.Visible = true;
                    cmdEdit1.Visible = true;
                    cmdDelete1.Visible = true;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = false;

                    PanelRadGrid1.Visible = true;
                    PanelEdit1.Visible = false;
                    break;
                case "AddNew":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;

                    DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, true, null, null);
                    DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, null, false, 800, null);
                    DropDownList_IcmPoSeqContract.LoadControl(600, null, txtBgmYear.Text);
                    DropDownList_IcmPoSeqPrepay.LoadControl(600, null, txtBgmYear.Text);
                    ddlIcmBidSeq.Enabled = true;
                    ddlIcmBidSeqOffer.Enabled = true;
                    DropDownList_IcmPoSeqContract.SetComboBoxEnable(true);
                    DropDownList_IcmPoSeqPrepay.SetComboBoxEnable(true);
                    break;
                case "Edit":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;

                    DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, true, null, null);
                    DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, null, false, 800, null);
                    DropDownList_IcmPoSeqContract.LoadControl(600, null, txtBgmYear.Text);
                    DropDownList_IcmPoSeqPrepay.LoadControl(600, null, txtBgmYear.Text);
                    ddlIcmBidSeq.Enabled = false;
                    ddlIcmBidSeqOffer.Enabled = false;
                    DropDownList_IcmPoSeqContract.SetComboBoxEnable(false);
                    DropDownList_IcmPoSeqPrepay.SetComboBoxEnable(false);                   

                    break;
            }
        }

        private void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();
        }

        private void LoadDDLFilterReceiveType()
        {
            ddlFilterReceiveType.SelectedIndex = 0;
        }

        private void LoadDDLReceiveTypeSeq()
        {
            ddlReceiveTypeSeq.DataSource = type.GetList(ddlFilterBgmSourceSeq.SelectedValue);
            ddlReceiveTypeSeq.DataBind();

            ddlReceiveTypeSeq.SelectedIndex = 0;
            ddlReceiveTypeSeq_SelectedIndexChanged(null, null);
        }

        private void LoadRBLMethodSeq()
        {
            var models = m.GetList();

            if (models.Count > 3)
            {
                var newModels = new List<M_FIM_MAS_Methods>();
                for (int i = 0; i < 3; i++)
                {
                    newModels.Add(models[i]);
                }
                models = newModels;
            }

            rblMethodSeq.DataSource = models;
            rblMethodSeq.DataBind();
        }

        private void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList(null, ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlBankAccSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlBankAccSeq);
            ddlBankAccSeq.SelectedIndex = 0;
        }

        private void LoadBank()
        {
            ddlBank.DataSource = bank.GetList();
            ddlBank.DataBind();
        }

        private void RblModeSelectChanged()
        {
            string strMode = rblMode.SelectedValue;
            PanelReturn.Visible = strMode == "1";
            PanelIncome.Visible = strMode == "2";
            PanelPetition.Visible = strMode == "3";

            if (strMode == "3")
            {
                rblMethodSeq.SelectedValue = "3";
                rblMethodSeq.Enabled = false;
                rblMethodSeq_SelectedIndexChanged(null, null);
                pnReceipt.Visible = false;
            }
            else
            {
                rblMethodSeq.Enabled = true;
                pnReceipt.Visible = true;
                //Adding ให้เลือกเงินโอนเป็นค่าตั้งต้น
                rblMethodSeq.SelectedValue = "3";
            }

            switch (strMode)
            {
                case "1":
                    lblModeName.Text = "รับเงินเบิกเกิน";
                    break;
                case "2":
                    lblModeName.Text = "รับเงินรายได้";
                    break;
                case "3":
                    lblModeName.Text = "รับจากรายการขอเบิก";
                    break;
            }           
        }

        private void LoadRadGrid1()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strRecvTypeSeq = ddlFilterReceiveType.SelectedValue;

            var data = r.GetFull(strBgmSourceSeq, null, strBgmYear, strRecvTypeSeq).OrderByDescending(o => o.receive_seq);
            RadGrid1.DataSource = data;

            GridSortExpression expression = new GridSortExpression();
            expression.FieldName = "receive_date";
            expression.SetSortOrder("Descending");
            RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);

        }

        private void ClearControl1()
        {
            lblReceiveSeq.Text = "";
            txtReceiptNo.Text = "";
            DropDownList_Contact1.SetSelectedValue("");
            DropDownList_Emp1.SetSelectedValue("");
            txtTempContact.Text = "";
            txtRemarks.Text = "";
            txtAmount.Text = "";
            lblAmount2.Text = "0.00";
            txtVatAmount.Text = "";
            txtExcludeVatAmount.Text = "";
            txtVatPercent.Text = "";
            txtTaxPercent.Text = "";
            txtTaxAmount.Text = "";
            txtIncludeVatAmount.Text = "";

            txtQty.Text = "";
            txtUnitPrice.Text = "";
        }

        private void ClearItems()
        {
            txtItemDtlName.Text = "";
            txtQtyItem.Text = "";
            txtUnitItem.Text = "";
            txtSumPrice.Text = "";
        }

        private void CalculateVat()
        {
            decimal dIncludeVatAmount = 0;
            decimal dVatPercent = 0;
            decimal dTaxPercent = 0;
            decimal dExcludeVatAmount = 0;
            decimal dVatAmount = 0;
            decimal dTaxAmount = 0;
            decimal dAmount = 0;
            decimal dDiscountPercent = 0;
            decimal dUnitPrice = 0;
            decimal dQty = 0;
                        
            //if (txtQty.Text.Trim() != "" && txtUnitPrice.Text.Trim() != "")
            //{
            //    txtIncludeVatAmount.Text = (decimal.Parse(txtQty.Text.Trim()) * decimal.Parse(txtUnitPrice.Text.Trim())).ToString();
            //}         

            if (!decimal.TryParse(txtIncludeVatAmount.Text, out dIncludeVatAmount))
            {
                return;
            }

            decimal.TryParse(txtVatPercent.Text, out dVatPercent);
            decimal.TryParse(txtTaxPercent.Text, out dTaxPercent);
            decimal.TryParse(txtDiscRate.Text, out dDiscountPercent);
            decimal.TryParse(txtVatAmount.Text, out dVatAmount);
            decimal.TryParse(txtExcludeVatAmount.Text,out dExcludeVatAmount);
            decimal.TryParse(txtUnitPrice.Text, out dUnitPrice);
            decimal.TryParse(txtQty.Text, out dQty);

            if( this._vatChangeFlag )
            {
                dUnitPrice = setValueNumber((dIncludeVatAmount / dQty) * (100 / (100 + dVatPercent)));
                decimal dPre = dUnitPrice * dQty;                

                //dPre = Math.Round(dPre, 2);
                //string[] strPre = dPre.ToString().Split('.');

                //if (strPre.Length > 1 && strPre[1].Length > 2)
                //{
                //    strPre[1] = strPre[1].Substring(0, 2);
                //    dPre = Convert.ToDecimal(strPre[0] + "." + strPre[1]);
                //}                

                dExcludeVatAmount = setValueNumber(dPre);
                this._vatChangeFlag = false;                                
            }
            
            dTaxAmount = dExcludeVatAmount * dTaxPercent / 100;
            
            decimal dDiscount = (dIncludeVatAmount * dDiscountPercent) / 100;

            dAmount = dIncludeVatAmount - dTaxAmount - dDiscount;

            txtTaxAmount.Text = dTaxAmount.ToString("#,##0.00");
            txtAmount.Text = dAmount.ToString("#,##0.00");            
            txtDiscRate.Text = dDiscountPercent.ToString("#,##0.00");
            txtDiscount.Text = dDiscount.ToString("#,##0.00");
            txtUnitPrice.Text = dUnitPrice.ToString("#,##0.00");
            
            if (dIncludeVatAmount > 0 && dVatPercent == 0)
            {
                txtExcludeVatAmount.Text = dIncludeVatAmount.ToString("#,##0.00");
            }
            else
            {
                txtExcludeVatAmount.Text = dExcludeVatAmount.ToString("#,##0.00");
                dVatAmount = dIncludeVatAmount - dExcludeVatAmount;                
            }
            txtVatAmount.Text = dVatAmount.ToString("#,##0.00");

        }

        private void LoadBranch()
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                ddlBranch.DataSource = branch.GetList(ddlBank.SelectedValue);
                ddlBranch.DataBind();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }
        }

        private void RecivLog_Insert(M_FIM_Receives model,string recordStatus,string remark)
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strSQL = string.Format("insert into fim_receives_log (receivelog_date,bgm_year,receipt_no,ref_no,receivelog_remark,record_status,receive_mode,input_source,created_by,created_when,receive_seq,bgm_source_seq) values ('{0}',{1},'{2}','{3}','{4}','{5}','{6}','{7}',{8},'{9}',{10},{11})"
                , string.Format("{0}-{1}-{2}", (DateTime.Today).Year > 2500 ? (DateTime.Today).Year - 543 : (DateTime.Today).Year, (DateTime.Today).Month, (DateTime.Today).Day)
                , model.bgm_year, model.receipt_no, model.ref_no, remark, recordStatus, model.receive_mode, model.source == null ? "Canceled": model.source, model.created_by
                , string.Format("{0}-{1}-{2}", model.created_when.Value.Year > 2500 ? model.created_when.Value.Year - 543 : model.created_when.Value.Year, model.created_when.Value.Month, model.created_when.Value.Day),model.receive_seq,model.bgm_source_seq);

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                using (SqlCommand cmd = new SqlCommand(strSQL,conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private void RecivLog_Deleted(M_FIM_Receives model)
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strSQL = string.Format("update fim_receives_log set record_status = '{0}',updated_by = {1},updated_when = '{2}' where receive_seq = {3}"
                                           , "D", model.updated_by
                                           , string.Format("{0}-{1}-{2}", model.updated_when.Value.Year > 2500 ? model.updated_when.Value.Year - 543 : model.updated_when.Value.Year, model.updated_when.Value.Month, model.updated_when.Value.Day)
                                           , model.receive_seq);

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private void RecivLog_Update(string receiveSeq, string strUserID)
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strSQL = string.Format("update fim_receives_log set record_status = '{0}',updated_by = {1},updated_when = '{2}' where receive_seq = {3}"
                                           , "C", strUserID, string.Format("{0}-{1}-{2}"
                                           , (DateTime.Today).Year > 2500 ? (DateTime.Today).Year - 543 : (DateTime.Today).Year, (DateTime.Today).Month, (DateTime.Today).Day)
                                           , receiveSeq);

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private void Receives_Update(string receiveSeq, string strUserID)
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strSQL = string.Format("update fim_receives set record_status = '{0}',updated_by = {1},updated_when = '{2}' where receive_seq like '{3}'"
                                           , "C", strUserID, string.Format("{0}-{1}-{2}"
                                           , (DateTime.Today).Year > 2500 ? (DateTime.Today).Year - 543 : (DateTime.Today).Year, (DateTime.Today).Month, (DateTime.Today).Day)
                                           , receiveSeq);

            using (SqlConnection conn = new SqlConnection(strConn))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private string getInvNo()
        {
            DataTable dt = new DataTable();
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strQry = "select top 1 receipt_no"
                            + " from fim_receives_log"
                            + " where	receive_mode = 2"
                            + " order by receipt_no desc";
            string invNo = "";


            using(SqlConnection con = new SqlConnection(strConn))
            {
                if(con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using(SqlDataAdapter adp = new SqlDataAdapter(strQry,con))
                {
                    adp.Fill(dt);
                }
            }

            if(dt.Rows.Count > 0)
            {
                invNo = dt.Rows[0][0].ToString();
            }

            return invNo;
        }

        private string getReceiveSeq()
        {
            DataTable dt = new DataTable();
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strQry = "select top 1 receive_seq"
                            + " from fim_receives"
                            + " order by receive_seq desc";
            string recvSeq = "";


            using (SqlConnection con = new SqlConnection(strConn))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using (SqlDataAdapter adp = new SqlDataAdapter(strQry, con))
                {
                    adp.Fill(dt);
                }
            }

            if (dt.Rows.Count > 0)
            {
                recvSeq = dt.Rows[0][0].ToString();
            }

            return recvSeq;
        }

        private DataTable getInvItems(string receive_seq)
        {
            DataTable dt = new DataTable();
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string strQry = "select ROW_NUMBER()OVER(ORDER BY receive_seq) as item_seq,receive_dtls_name,qty,unit_price,amount"
                            + " from fim_receive_dtls"
                            + " where receive_seq = "+receive_seq;
           
            using (SqlConnection con = new SqlConnection(strConn))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using (SqlDataAdapter adp = new SqlDataAdapter(strQry, con))
                {
                    adp.Fill(dt);
                }
            }

            return dt;
        }

        private void insInvItems()
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];            

            if (tmpRecvSeq > 0)
            {
                string strSQL = string.Format("insert into fim_receive_dtls (receive_seq,receive_dtls_name,qty,unit_price,amount,record_status) values ({0},'{1}',{2},{3},{4},'{5}')"
                    , tmpRecvSeq, txtItemDtlName.Text.Trim(), txtQtyItem.Text.Trim(), txtUnitItem.Text.Trim(), txtSumPrice.Text.Trim(), "W");

                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }

                    using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }

                dtInvItems = getInvItems(tmpRecvSeq.ToString());
            }
        }

        private void updInvItems(string ReceiveSeq)
        {
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];

            if (tmpRecvSeq > 0)
            {
                string strSQL = string.Format("update fim_receive_dtls set receive_seq = {0} where receive_seq = {1}"
                    , ReceiveSeq, tmpRecvSeq);

                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }

                    using (SqlCommand cmd = new SqlCommand(strSQL, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }               
            }
        }

        private DataTable CreateDataTableInvDtl()
        {
            DataTable myDataTable = new DataTable();

            DataColumn myDataColumn;

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.Int32");
            myDataColumn.ColumnName = "item_seq";
            myDataTable.Columns.Add(myDataColumn);

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.String");
            myDataColumn.ColumnName = "receive_dtls_name";
            myDataTable.Columns.Add(myDataColumn);

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.Int32");
            myDataColumn.ColumnName = "qty";
            myDataTable.Columns.Add(myDataColumn);

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.Double");
            myDataColumn.ColumnName = "unit_price";
            myDataTable.Columns.Add(myDataColumn);
            
            return myDataTable;
        }

        #endregion

        #region Public Methods

        public void ddlIcmBidSeqSetSelectedValue(string strValue, string strContactSeq)
        {
            if (strValue.Length > 0)
            {
                if (ddlIcmBidSeq.FindItemByValue(strValue) == null)
                {
                    M_ICM_Bidder info = bidder.GetInfo(strValue);
                    ddlIcmBidSeq.Text = info.icm_bid_name;
                    lblIcmBidRecSeq.Text = info.icm_bid_seq.ToString();
                }
                else
                {
                    ddlIcmBidSeq.SelectedValue = strValue;
                }
            }
            else
            {
                ddlIcmBidSeq.SelectedIndex = -1;
                ddlIcmBidSeq.Text = "";
            }

            if (strContactSeq != null)
            {
                DropDownList_Contact1.SetSelectedValue(strContactSeq);
                lblContactSeq.Text = strContactSeq;
            }
            else
            {
                DropDownList_Contact1.SetSelectedValue("");
                lblContactSeq.Text = "";
            }
        }

        public void LoadIcmBidSeq(RadComboBoxItemsRequestedEventArgs e)
        {
            string strFilter = e.Text;
            string strBgmYearSeq = txtBgmYear.Text;
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            //string strStep = (lblStep.Text.Length > 0 ? lblStep.Text : null);
            string strDate = dpReceiveDate.GetStringValue();
            IList<M_ICM_Bid> infolist = new List<M_ICM_Bid>();

            infolist = bid.GetReceiveList(strBgmYearSeq, strDate, strFilter);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + nOffset, infolist.Count);
            e.EndOfItems = endOffset == infolist.Count;

            for (int i = itemOffset; i < endOffset; i++)
            {
                ddlIcmBidSeq.Items.Add(new RadComboBoxItem(infolist[i].icm_bid_name, infolist[i].icm_bid_seq.ToString()));
            }

            e.Message = main.GetStatusMessage(endOffset, infolist.Count);
        }

        public void LoadIcmBidSeqOffer(RadComboBoxItemsRequestedEventArgs e)
        {
            string strFilter = e.Text;
            string strBgmYearSeq = txtBgmYear.Text;
            //string strReceiveType = (lblReceiveType.Text.Length > 0 ? lblReceiveType.Text : null);
            //string strStep = (lblStep.Text.Length > 0 ? lblStep.Text : null);
            string strDate = dpReceiveDate.GetStringValue();
            IList<M_ICM_Bid> infolist = new List<M_ICM_Bid>();

            infolist = bid.GetOfferList(strBgmYearSeq, strDate, strFilter);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + nOffset, infolist.Count);
            e.EndOfItems = endOffset == infolist.Count;

            for (int i = itemOffset; i < endOffset; i++)
            {
                ddlIcmBidSeqOffer.Items.Add(new RadComboBoxItem(infolist[i].icm_bid_name, infolist[i].icm_bid_seq.ToString()));
            }

            e.Message = main.GetStatusMessage(endOffset, infolist.Count);
        }

        public void ddlIcmBidSeqOfferSetSelectedValue(string strValue, string strContactSeq)
        {
            if (strValue.Length > 0)
            {
                M_ICM_BidOfferCollateral info = bidderCol.GetInfo(strValue);

                if (ddlIcmBidSeqOffer.FindItemByValue(strValue) == null)
                {
                    ddlIcmBidSeqOffer.Text = info.icm_bid_name;
                    lblIcmBidOffColSeq.Text = info.icm_bid_seq.ToString();
                }
                else
                {
                    ddlIcmBidSeqOffer.SelectedValue = strValue;
                }
            }
            else
            {
                ddlIcmBidSeqOffer.SelectedIndex = -1;
                ddlIcmBidSeqOffer.Text = "";
            }

            if (strContactSeq != null)
            {
                DropDownList_Contact1.SetSelectedValue(strContactSeq);
                lblContactSeq.Text = strContactSeq;
            }
            else
            {
                DropDownList_Contact1.SetSelectedValue("");
                lblContactSeq.Text = "";
            }
        }

        public decimal setValueNumber(decimal value)
        {
            string[] strPre = value.ToString().Split('.');

            if (strPre.Length > 1 && strPre[1].Length > 2)
            {
                strPre[1] = strPre[1].Substring(0, 2);
                value = Convert.ToDecimal(strPre[0] + "." + strPre[1]);
            }

            return value;
        }

        #endregion       

        protected void lbtnAddItmDetails_Click(object sender, EventArgs e)
        {
            if (txtQtyItem.Text.Trim() != "" && txtUnitItem.Text.Trim() != "")
            {
                insInvItems();
            }

            radInvItems.MasterTableView.Rebind();
            ClearItems();
        }

        protected void grdMoneyRequestDtls_ItemCommand(object sender, GridCommandEventArgs e)
        {

        }

        protected void txtReceiveDtlsAmount_TextChanged(object sender, EventArgs e)
        {
            double dSumAmount = 0;

            foreach (GridDataItem item in grdMoneyRequestDtls.Items)
            {
                RadNumericTextBox txtReceiveDtlsAmount = (RadNumericTextBox)item.FindControl("txtReceiveDtlsAmount");
                double dAmount = txtReceiveDtlsAmount.Value ?? 0;
                dSumAmount += dAmount;
            }

            lblAmount2.Text = dSumAmount.ToString("#,##0.00");
        }
    }
}